Video Modals are a common way of displaying a new feature of your product or even to present your visitors something else. YouTube API provides us with a better control over videos hosted on YouTube. In this tutorial we will create a Video Modal using WordPress shortcodes. By setting a shortcode in our content, we will display a button that will open a video in a modal.

We will create a simple plugin that will enable our shortcode to be rendered as a button. You are free to customize it as you want or even create another shortcode to display a video inside the content.

Try this plugin right now by downloading it here: youtube-modal.

YouTube API

Before we begin, let’s learn more about the YouTube API here. The initial code present there will also be used in our plugin. I encourage you to read more about it there when you have time.

When starting our video, we will create a reference to the YouTube Player object. By doing that, we will be able to control the video by pausing it, stoping it or even loading another one.

Functions

We will now learn more about the YouTube API functions that we can use on our player object. This functions can be called like this:

player.loadVideoById({params});

I will list some of the functions here as a reference to what the YouTube API can do, but I will not go over them in details. If you would like to learn more about some of those functions, click on them.

Queuing Functions

  • loadVideoById – load a video by providing the YouTube ID. You can control when the video is going to start or end.
  • cueVideoByUrl – create the player from the URL. This will not load or start the player until you start it.
  • loadVideoByUrl – load the video from the URL. It loads and plays the video.

There are also functions for playlists that can be used in a similar way.

Playback Functions

Here are only some of the functions, but there are many more of them that can be used with YouTube API. I will show you some that may interest you when working with a video.

  • playVideo – plays the video or resumes the video if paused
  • pauseVideo – pauses the video
  • stopVideo – stops the video
  • seekTo – plays the video on a set number of seconds. If the video is not buffered on that time, you can set it to buffer ahead
  • mute
  • unMute
  • setVolume – pass an integer from 0 to 100
  • getVolume

Playback Status

This functions are indicators that will show us the status of our video.

  • getVideoLoadedFraction – gets a number between 0 and 1 that will indicate a percentage of how much our video has been buffered
  • getPlayerState – gets the state of our player (video):
    • -1: unstarted
    • 0: ended
    • 1: playing
    • 2: paused
    • 3: buffering
    • 5: video cued
  • getCurrentTime – get current time

I would encourage you to read more about other functions because the YouTube API provides you with possibly everything you need from a video.

Events

Events are another interesting part of the YouTube API. We can define functions that will be called once an event occurs in our video or player. Each event object has a target that is a reference to our player.

  • onReady – when player has finished loading and is ready for YouTube API calss
  • onStateChange – when the state of our player changes
  • onPlaybackQualityChange – when the quality of our player changes
  • onPlaybackRateChange – when the rate changes
  • onError – when an error occurs in our player
  • onApiChange – when a module has been loaded in the player. At the time of writing only the captions module existed

You should the section onApiChange to learn more about the captions module. You should also look other sections, especially onError. We will define a function for that event and alert the visitor of any error.

Parameters

Parameters are a big thing here. They allow us to control the display and functionality of our video. In our tutorial we will create a shortcode that can include all of those parameters. Since there are a lot of those, I will just show you some of them:

  • fs – enable/disable the fullscreen option
  • colors – control the color of our video (red or white loading bar)
  • controls – display or hide the controls
  • modestbranding – display or hide the YouTube logo
  • showinfo – display or hide the information on the video (title)

WordPress Plugin

Now that we learned a little about the YouTube API, we can start coding. The first thing you will have to do is create a new plugin folder youtube-modal. In that folder create a new file with the same name youtube-modal.php and add this:

Save that and go to your WordPress admin dashboard and under the Plugins menu, activate our plugin “WordPress Video Pop-up with YouTube API”.

WordPress Shortcode

We will start by creating our shortcode. We will accept any attribute we put in that shortcode and once it it loaded, we will add all those attribute as a HTML data attribute. By doing that, we will be able to use JavaScript and dynamically set the parameters for our video using the YouTube API.

Add this code to that file:

We check for the ID attribute first. If there is none, we will not display the button because we can’t have a YouTube video without an ID. After that we are creating the object string of every attribute that is set. We are then returning the button HTML with two attributes:

  • onClick – this attribute will call the JavaScript function openVideoFromShortcode every time a user clicks on the button
  • data-vars – the data attribute that will hold every parameter we set inside the shortcode

We are registering our shortcode function with the add_shortcode. First parameter is the shortcode name that we will use inside our content.

WordPress Video Modal

Now we will also add the modal. We will have an element that is empty and it will be replaced by the video iframe using the YouTube API.

By using the action hook wp_footer, we will add this modal to the footer. We will hide that modal initially and by adding a class to the html we will show this modal and create a video in it.

The button in this modal will be also use to close the modal by calling the JavaScript function closeVideo.

Style for the modal

We will now also add the style in the same way as the modal, but in the head of the page. Since this is a small style, we are making it inline instead of placing it in a separate css file. That way we will save on HTTP request.

For production, you could also minify that CSS.

The class modal-open that will be applied on the html will be the indicator that the modal should show. By using the ::before, we are also adding a black background with some opacity under the modal. This will make the modal stand out.

Coding with the YouTube API

This is the last part of our tutorial. Great job reading the article all the way! Now we will create all the JavaScript functions that we need for our WordPress Video modal to show and display the YouTube video.

Since this is also a small script, we will place it at the bottom of our page. I also suggest minifying this script for production.

Add this as a base:

This is the same script that YouTube API documentation gives for getting started. This is will create a their script to load asynchronous. Once it is loaded, it will make the variable youtubeApiLoaded as true. We will use that as an indicator if we can start our video or not.

The Shortcode Function: openVideoFromShortcode

This is the function that will be called once your visitor clicks the button. We are first getting all the attributes from our button.

Two default variables varsValue and idValue will hold the ID for our YouTube video and also the player parameters. Since we don’t know at which place is our data-vars, we must iterate through all the attributes and find it.

Once we find it, we are breaking out of the loop and we are also setting the value from that attribute in the variable varsValue. By using the JSON.parse, we are creating a JavaScript object from that value. From that object, we are also getting the ID of our YouTube video.

The last step is to call the function createPlayer that will create show the modal and create the video using YouTube API.

Function createPlayer

This function is used to create the player.

We are checking our indicator if the YouTube API has been loaded. Also, if the ID is not set, we will not create the video. If everything is fine, we are creating a new video using the YouTube API and setting the creating object to the global variable player.

Some functions are also applied to the events. We are passing the ID to the videoId and we are also passing all our parameters through variable vars to playerVars.

Function onPlayerReady

YouTube API will call this function when the player is ready to start the video. We will start the video and also add the class modal-open to the html node.

Function onPlayerStateChange

We are here looking at the state of our player. If our video has stopped playing, we are calling the function closeVideo. This function will remove the class modal-open and also destroy our player.

Function closeVideo

In this function we are first destroying the video. This will remove the whole iframe object from our DOM. We are then getting the html node and if there is a class modal-open, we remove it.

Function onPlayerError

This function will alert the user when there is an error with our video/player.

The YouTube API documentation has all the error codes explained.

Example of shortcode

[youtube_button  id=V6O1eS0BQpo text="Video" fs="0"  color=white modestbranding=1 showinfo=0]

This shortcode example will display a YouTube video with the ID V6O1eS0BQpo. The text on the button will be Video. We will also remove the full screen option, YouTube logo and the video information. I also chose the color white as the video seeking bar.

Conclusion

YouTube API is a great way of displaying YouTube videos in your website because you get more control over it. Using the WordPress shortcode feature, we can place our button in various content and get a great YouTube Video.

Now you have a good base of displaying YouTube videos dynamically. If you want to display them in some other way, you can always create another function. You just need to call the function createPlayer and pass the id. Parameters do not need to be set, so they can always be empty.

Become a Sponsor

Posted by Igor Benic

Web Developer who mainly uses WordPress for projects. Working on various project through Codeable & Toptal. Author of several ebooks at https://leanpub.com/u/igorbenic.

3 Comments

  1. Your short-code example has disappeared?

    Reply

    1. Hi Anabel, it should be up again:) Sorry for that!

      Reply

  2. Thanks for this tutorial! Great help 🙂

    Just one note: The example shortcode has an impossible combination of color=white and modestbranding=1.

    See the note on the parameter in the documentation:
    “Note: Setting the color parameter to white will disable the modestbranding option.”
    https://developers.google.com/youtube/player_parameters#color

    Reply

Leave a reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.